package com.carkeeper.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.dto.AppraisalDTO;
import com.carkeeper.dto.OrderDTO;
import com.carkeeper.dto.OrderDetailDTO;
import com.carkeeper.exception.BussinessException;
import com.carkeeper.pojo.MAppraisalPO;
import com.carkeeper.service.OrderAppraisalService;
import com.carkeeper.service.OrderFeign;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: chaolumen
 * @date ：Created in 2020/5/26
 * @description ：评价业务实现类
 * @version: 1.0
 */

@Service
public class OrderAppraisalServiceImpl implements OrderAppraisalService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private OrderFeign orderFeign;

    @Override
    public void add(MAppraisalPO mpo) {
        //封装基础信息
        mpo.setId(UUID.randomUUID().toString());  //评价id
        mpo.setCreateTime(LocalDateTime.now());   //创建时间

        //封装订单信息
        OrderDTO order = orderFeign.getOrder(mpo.getOrderId());
        if (order != null) {
            mpo.setStoreId(order.getStoreId());
            mpo.setStoreType(order.getType());
            mpo.setStoreSimpleName(order.getStoreName());
            mpo.setOrderCode(order.getCode());
            mpo.setCustomorId(order.getUserId().longValue());
            mpo.setCustomorName(order.getContact());
            if (order.getMoney() != null) {
                BigDecimal weight = new BigDecimal(100);
                BigDecimal money = new BigDecimal(order.getMoney());
                mpo.setServiceCost(money.divide(weight, 2, RoundingMode.HALF_UP));
            }
            mpo.setOrderCreateTime(order.getCreateTime());
            if (order.getOrderDetailPOList() != null) {
                String serviceClassName = null;
                List<OrderDetailDTO> orderDetailDTOList = order.getOrderDetailPOList();
                StringBuilder serviceItemBuilder = new StringBuilder();
                for (OrderDetailDTO orderDetailDTO : orderDetailDTOList) {
                    if (serviceItemBuilder.length() > 0) {
                        serviceItemBuilder.append(",");
                    }
                    serviceItemBuilder.append(orderDetailDTO.getName());
                    serviceClassName = orderDetailDTO.getType();
                }
                mpo.setServiceItems(serviceItemBuilder.toString());
                mpo.setServiceClassName(serviceClassName);
            }
        } else {
            throw new BussinessException("订单信息有误！！");
        }


        mongoTemplate.save(mpo);

    }


    @Override
    public Page<MAppraisalPO> findAll(Long page,
                                      Long pageSize,
                                      String storeType,
                                      String orderCode,
                                      String customorName,
                                      Integer serviceTypeStatus,
                                      String orderTimeStart,
                                      String orderTimeEnd,
                                      String storeName,
                                      Long storeId) {
        Page<MAppraisalPO> pa = new Page(page, pageSize);

        Criteria criteria = new Criteria();

        //订单编号判断
        if (!StringUtils.isEmpty(orderCode)) {
            criteria.and("orderCode").regex(orderCode);
        }

        //服务分类判断
        if (!StringUtils.isEmpty(storeType)) {
            criteria.and("storeType").regex(storeType);
        }

        //判断订单时间区间
        if (orderTimeStart != null && orderTimeEnd != null) {
            LocalDate startLocalDate = LocalDate.parse(orderTimeStart, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate endLocalDate = LocalDate.parse(orderTimeEnd, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            criteria.andOperator(
                    Criteria.where("orderCreateTime").gte(startLocalDate),
                    Criteria.where("orderCreateTime").lte(endLocalDate)
            );
        } else {
            if (orderTimeStart != null) {
                LocalDate startLocalDate = LocalDate.parse(orderTimeStart, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                criteria.andOperator(
                        Criteria.where("orderCreateTime").gte(startLocalDate)
                );
            }
            if (orderTimeEnd != null) {
                LocalDate endLocalDate = LocalDate.parse(orderTimeEnd, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                criteria.andOperator(
                        Criteria.where("orderCreateTime").lte(endLocalDate)
                );
            }
        }

        //服务门店名称的判断
        if (!StringUtils.isEmpty(storeName)) {
            criteria.and("storeSimpleName").regex(storeName);
        }

        //客户名称的判断
        if (!StringUtils.isEmpty(customorName)) {
            criteria.and("customorName").regex(customorName);
        }

        if (storeId != null) {
            criteria.and("storeId").is(storeId);
        }

        Query query = new Query();
        query.skip((pa.getCurrent() - 1) * pa.getSize()).limit((int) pa.getSize()).addCriteria(criteria);
        List<MAppraisalPO> list = mongoTemplate.find(query, MAppraisalPO.class);
        Query countQuery = new Query();
        countQuery.addCriteria(criteria);
        long totalSize = mongoTemplate.count(countQuery, MAppraisalPO.class);
        pa.setTotal(totalSize);

        pa.setRecords(list);
        return pa;
    }


    @Override
    public MAppraisalPO findById(String id) {
        return mongoTemplate.findById(id, MAppraisalPO.class);
    }

    @Override
    public Boolean deleteAppraisalById(String id) {
        MAppraisalPO mpo = new MAppraisalPO();
        mpo.setId(id);
        return mongoTemplate.remove(mpo).wasAcknowledged();
    }

    @Override
    public List<AppraisalDTO> getByIds(List<String> ids) {
        List<AppraisalDTO> dtoList = new ArrayList<>();
        if (ids != null) {

            Criteria criteria = new Criteria();
            criteria.and("_id").in(ids);
            Query query = new Query();
            query.addCriteria(criteria);
            List<MAppraisalPO> list = mongoTemplate.find(query, MAppraisalPO.class);
            for (MAppraisalPO po : list) {
                AppraisalDTO dto = new AppraisalDTO();
                BeanUtils.copyProperties(po, dto);
                dtoList.add(dto);
            }
        }
        return dtoList;
    }
}
